/**
    Copyright (c) 2010 yakiimo02
    Distributed under the New BSD License.
    See included license.txt or http://www.yakiimo3d.com/NewBSDLicense.txt
**/

/**
    @file   
    @brief  Reduce input 2D texture to a 1D buffer.
            Based on DirectX SDK's HDRToneMappingCS11 sample's ReduceTo1DCS.hlsl 
    @author yakiimo02
    @date   2010/03/07
*/

StructuredBuffer<float4>        Input        : register( t0 ); 
RWStructuredBuffer<float2>    Result        : register( u0 );

cbuffer cbCS : register( b0 )
{
    uint4    g_param;   // (g_param.x, g_param.y) is the x and y dimensions of the Dispatch call
                        // (g_param.z, g_param.w) is the size of the above Input Texture2D
};

#define blocksize 8
#define blocksizeY 8
#define groupthreads (blocksize*blocksizeY)
groupshared float2 accum[groupthreads];

//static const float3 LUM_VECTOR = float3(.299, .587, .114);
static const float3 LUM_VECTOR = float3(0.265068, 0.67023428, 0.06409157);


[numthreads(blocksize,blocksizeY,1)]
void CSMain( uint3 Gid : SV_GroupID, uint3 DTid : SV_DispatchThreadID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex )
{    
    float4 s = Input[ (DTid.y*g_param.z)+DTid.x ];
    
    const float EPSILON = 0.00001;
   
    float luminance = dot( s.xyz, LUM_VECTOR.xyz );
      
    accum[GI].x = log( EPSILON + luminance );
    accum[GI].y = luminance; 

    // Each compute shader thread should be mapped to a single pixel in the input image.
    // Ignore threads not assigned to a pixel in the input image.
    if( ( DTid.y*g_param.z + DTid.x ) > g_param.z*g_param.w ) {
        accum[GI].x = 0.0;
        accum[GI].y = 0.0;
    }
    
    // Parallel reduction algorithm follows 
    GroupMemoryBarrierWithGroupSync();
    if ( GI < 32 ) {
        accum[GI].x += accum[32+GI].x;
        accum[GI].y = max( accum[GI].y, accum[32+GI].y );
    }

    GroupMemoryBarrierWithGroupSync();
    if ( GI < 16 ) {
        accum[GI].x += accum[16+GI].x;
        accum[GI].y = max( accum[GI].y, accum[16+GI].y );
    }

    GroupMemoryBarrierWithGroupSync();
    if ( GI < 8 ) {
        accum[GI].x += accum[8+GI].x;
        accum[GI].y = max( accum[GI].y, accum[8+GI].y );
    }

    GroupMemoryBarrierWithGroupSync();
    if ( GI < 4 ) {
        accum[GI].x += accum[4+GI].x;
        accum[GI].y = max( accum[GI].y, accum[4+GI].y );
    }

    GroupMemoryBarrierWithGroupSync();
    if ( GI < 2 ) {
        accum[GI].x += accum[2+GI].x;
        accum[GI].y = max( accum[GI].y, accum[2+GI].y );
    }

    GroupMemoryBarrierWithGroupSync();
    if ( GI < 1 ) {
        accum[GI].x += accum[1+GI].x;
        accum[GI].y = max( accum[GI].y, accum[1+GI].y );
    }

    if( GI == 0 )
    {
        Result[Gid.y*g_param.x+Gid.x] = accum[0];
    }
}
